// import Vue from "vue";
import VueRouter from "vue-router";
import Cookies from "js-cookie";
import { getDgutToken } from "../network";
const Login = () => import("@/components/Login.vue");
const Form = () => import("@/components/Form.vue");
const Test = () => import("@/components/Test.vue");

// Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
    beforeEach: (to, from, next) => {
      next();
    },
  },
  {
    path: "/form",
    name: "Form",
    component: Form,
  },
  {
    path: "/login/dgut",
    name: "Test",
    component: Test,
  },
];

const router = new VueRouter({
  routes,
  mode: "history",
});

// 每一次进入的时候判断cookie有没有token
router.beforeEach((to, from, next) => {
  // 使用js-cookie存取cookie
  let token = Cookies.get("token");

  if (to.path === "/" || to.path === "/login") {
    if (token != null && token != "" && token != undefined) {
      next("/form");
    }
    next();
  } else {
    if (token != null && token != "" && token != undefined) {
      next();
    } else {
      //中央认证获取token
      if (to.path === "/login/dgut") {
        let token = to.query.token;
        console.log(to.query.token);
        getDgutToken(token)
          .then((res) => {
            //中央认证成功
            if(res.data.code>=200 && res.data.code<300){
              let resToken = res.data.data;
              Cookies.set('token',resToken);
              next("/form");
            }else throw new Error(res.data);
          })
          .catch((err) => {
            console.log(err);
          });
        next("/");
      } else {
        alert("请先登录");
        next("/");
      }
    }
  }
});

export default router;
